﻿using CommonLib.Attr;
using CommonLib.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace CommonLib.Util;

public static class SqlFactory
{
    private static readonly List<BaseLexer> Lexers = new();

    public static void Init(Assembly assembly)
    {
        var arr = assembly.ExportedTypes.Where(t => t.GetCustomAttribute<OrderAttribute>() != null).ToList();
        var com = Assembly.GetExecutingAssembly().ExportedTypes
            .Where(t => t.GetCustomAttribute<OrderAttribute>() != null).ToList();
        arr.AddRange(com);
        arr.Sort(delegate (Type a, Type b)
        {
            if (a.GetCustomAttribute<OrderAttribute>()!.Index > b.GetCustomAttribute<OrderAttribute>()!.Index) return 1;
            else if (a.GetCustomAttribute<OrderAttribute>()!.Index < b.GetCustomAttribute<OrderAttribute>()!.Index) return -1;
            else return 0;
        });
        Lexers.AddRange(arr.Select(a => (Activator.CreateInstance(a) as BaseLexer)!));
    }

    public static BaseLexer Create(string str)
    {
        foreach (var lexer in Lexers)
        {
            lexer.Init(str);
            if (lexer.Check()) return lexer;
        }
        Console.WriteLine(str);
        return new UnRecognizedLexer().Init(str);
    }
}
